/*
 * Galaxium Messenger
 * Copyright (C) 2008 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using Anculus.Core;

using Galaxium.Core;
using Galaxium.Client;

namespace Galaxium.GStreamer
{
	public class GStreamerSoundBackend: ISoundBackend
	{
		const int _maxPlayers = 5;
		
		Queue<GStreamerSoundPlayer> _playerQueue = new Queue<GStreamerSoundPlayer> (_maxPlayers);
		
		public void Initialize ()
		{
			GStreamerInterop.libgalaxium_gstreamer_init ();
		}
		
		public void Shutdown ()
		{
		}

		public ISoundPlayer Open (string filename)
		{
			if (_playerQueue.Count >= _maxPlayers)
			{
				GStreamerSoundPlayer old = _playerQueue.Dequeue ();
				
				old.Stop ();
				old.Dispose ();
			}
			
			IntPtr uriPtr = GLib.Marshaller.StringToPtrGStrdup (new Uri (filename).AbsoluteUri);
			IntPtr native = GStreamerInterop.libgalaxium_gstreamer_open (uriPtr);
            GLib.Marshaller.Free (uriPtr);
			
			if (native == IntPtr.Zero)
			{
				Log.Warn ("Unable to open player for file {0}", filename);
				return null;
			}
			
			GStreamerSoundPlayer player = new GStreamerSoundPlayer (native);
			_playerQueue.Enqueue (player);
			
			return player;
		}

		public bool IsSupportedFile (string filename)
		{
			return File.Exists (filename);
		}
		
		public bool IsAvailable ()
		{
			return true;
		}
	}
}